import api from '../../utils/api'

Page({
  data: {
    code: '',
    loading: false,
    checking: false,
    error: '',
    detail: null
  },

  onLoad(options) {
    const code = options.code || ''
    if (code) {
      this.setData({ code })
      this.fetchDetail(code)
    }
  },

  onCodeInput(e) {
    this.setData({ code: e.detail.value })
  },

  async onQuery() {
    const { code } = this.data
    if (!code) return
    this.fetchDetail(code)
  },

  async fetchDetail(code) {
    this.setData({ loading: true, error: '', detail: null })
    try {
      const res = await api.verification.query(code)
      this.setData({ detail: res })
    } catch (err) {
      const msg = (err && err.message) || '查询失败'
      this.setData({ error: msg })
      wx.showToast({ title: msg, icon: 'none' })
    } finally {
      this.setData({ loading: false })
    }
  },

  async onCheckIn() {
    const { detail, code, checking } = this.data
    if (!detail || !detail.can_check_in || checking) return
    this.setData({ checking: true })
    try {
      await api.verification.checkIn({ reservation_code: code, notes: '' })
      wx.showToast({ title: '核销成功', icon: 'success' })
      // refresh
      this.fetchDetail(code)
    } catch (err) {
      const msg = (err && err.message) || '核销失败'
      wx.showToast({ title: msg, icon: 'none' })
    } finally {
      this.setData({ checking: false })
    }
  }
})